package org.jeecg.modules.gudingzichan.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.gudingzichan.entity.Gudingzichan;
import org.jeecg.modules.gudingzichan.entity.GudingzichanChild;
import org.jeecg.modules.gudingzichan.service.IGudingzichanService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gudzcdrdygx.entity.HqGudzcDaorsjdygx;
import org.jeecg.modules.gudzcdrdygx.service.IHqGudzcDaorsjdygxService;
import org.jeecg.modules.louy.entity.HqLouy;
import org.jeecg.modules.louy.service.IHqLouyService;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecg.modules.yfFangj.entity.HqYfFangj;
import org.jeecg.modules.yfFangj.service.IHqYfFangjService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: gudingzichan
 * @Author: jeecg-boot
 * @Date: 2020-07-31
 * @Version: V1.0
 */
@Api(tags = "gudingzichan")
@RestController
@RequestMapping("/gudingzichan/gudingzichan")
@Slf4j
public class GudingzichanController extends JeecgController<Gudingzichan, IGudingzichanService> {
    @Autowired
    private IGudingzichanService gudingzichanService;

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private IHqLouyService hqLouyService;

    @Autowired
    private IHqYfFangjService hqYfFangjService;

    @Autowired
    private ISysDepartService sysDepartService;

	@Autowired
	private ISysUserService sysUserService;

    @Autowired
    private ISysCategoryService sysCategoryService;

    @GetMapping(value = "/niandzcqc")
    public Result<?> niandzcqc() {
        Gudingzichan gudingzichan = new Gudingzichan();
        gudingzichan.setQingczt("2");
        gudingzichanService.update(gudingzichan, null);
        return Result.ok("操作成功!");
    }

    @PutMapping(value = "/setYiqczc")
    public Result<?> setYiqczc(@RequestBody Map<String, String> datas) {
        String ids = datas.get("ids");
        for (String id: ids.split(",")
             ) {
            Gudingzichan gudingzichan = gudingzichanService.getById(id);
            if(gudingzichan != null) {
                gudingzichan.setQingczt("1");
                gudingzichanService.updateById(gudingzichan);
            }
        }

        return Result.ok("操作成功!");
    }

    // 大屏数据
    @GetMapping(value = "/dapsu_gudzc")
    public Result<?> dapsu_gudzc() {
        List<Map<String, Object>> result = new ArrayList<>();
        // val 部门表根节点的id
        List<SysDepart> list = sysDepartService.list(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getParentId, "1331571789934395393"));
        list.stream().forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("bummc", item.getDepartName());
            map.put("santybmbm", item.getOrgCode2());
            map.put("count", gudingzichanService.count(new LambdaQueryWrapper<Gudingzichan>().likeRight(Gudingzichan::getSysOrgCode, item.getOrgCode())));

            result.add(map);
        });

        return Result.ok(result);
    }

    @GetMapping(value = "/countHejsl")
    public Result<?> countHejsl(Gudingzichan gudingzichan, HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Page<Gudingzichan> page = new Page<>(0, -1);
        QueryWrapper<Gudingzichan> queryWrapper = QueryGenerator.initQueryWrapper(gudingzichan, req.getParameterMap());
        queryWrapper.likeRight("sys_org_code", loginUser.getOrgCode());

        queryWrapper.select("sum(shuliang) as total");
        Map map = gudingzichanService.getMap(queryWrapper);

        return Result.ok(map.get("total"));
    }

    @GetMapping(value = "/countHejje")
    public Result<?> countHejje(Gudingzichan gudingzichan, HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Page<Gudingzichan> page = new Page<>(0, -1);
        QueryWrapper<Gudingzichan> queryWrapper = QueryGenerator.initQueryWrapper(gudingzichan, req.getParameterMap());
        queryWrapper.likeRight("sys_org_code", loginUser.getOrgCode());

        queryWrapper.select("sum(jine) as total");
        Map map = gudingzichanService.getMap(queryWrapper);

        return Result.ok(map.get("total"));
    }

    String dig_parentId(String parentId) {
        SysDepart sysDepart = sysDepartService.getById(parentId);
        // 不显示根节点
        if(sysDepart != null && !sysDepart.getPid().equals("0")) {
            return dig_parentId(sysDepart.getParentId()) + "-" + sysDepart.getDepartName();
        }

        return "";
    }

    @GetMapping(value = "/findSysOrgParentName")
    public Result<?> findSysOrgParentName() {
        List<Map<String, Object>> list = new ArrayList<>();
        sysDepartService.list().stream().forEach(item -> {
            Map<String, Object> map = new HashMap<>();

            map.put("orgCode", item.getOrgCode2());
            map.put("departName", item.getDepartName());
            map.put("parentDepartName", dig_parentId(item.getParentId()));

            list.add(map);
        });

        return Result.ok(list);
    }

    @GetMapping(value = "/countByGudzcfl")
    public Result<?> countByGudzcfl(String gudzcfl) {
        int rtn = gudingzichanService.count(new LambdaQueryWrapper<Gudingzichan>().likeRight(Gudingzichan::getBianhao, gudzcfl));
        return Result.ok(rtn);
    }

    /**
     * 分页列表查询
     *
     * @param gudingzichan
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "gudingzichan-分页列表查询")
    @ApiOperation(value = "gudingzichan-分页列表查询", notes = "gudingzichan-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "gudingzichan/GudingzichanList")
    public Result<?> queryPageList(Gudingzichan gudingzichan,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Page<Gudingzichan> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Gudingzichan> queryWrapper = QueryGenerator.initQueryWrapper(gudingzichan, req.getParameterMap());
        QueryWrapper<Gudingzichan> wrapper=queryWrapper.orderByDesc("bianhao");
        IPage<Gudingzichan> pageList=gudingzichanService.page(page,wrapper);
//        IPage<Gudingzichan> pageList=null;
//        LoginUser user=(LoginUser)SecurityUtils.getSubject().getPrincipal();
//        if (!user.getUsername().equals("cscwzg")){
//            queryWrapper.eq("baoguanrenzh", user.getUsername());
//            pageList=gudingzichanService.page(page,queryWrapper);
//        }else {
//             pageList=gudingzichanService.page(page,queryWrapper);
//        }


//        queryWrapper.gt("zichan_status", 1);
//        queryWrapper.ne("delete_flag", 1);
//        IPage<Gudingzichan> pageList = page;
//        pageList.setRecords(gudingzichanIPage);

        pageList.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getGuanlbm());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setGuanlbm_fullName(fullName);

            fullName = this.dig_parentId(item.getDeptId());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setDeptId_fullName(fullName);
        });

        return Result.ok(pageList);
    }


    /**
     * 分页列表查询
     *
     * @param gudingzichan
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "myApplyList2-分页列表查询")
    @ApiOperation(value = "gudingzichan-分页列表查询", notes = "myApplyList2-分页列表查询")
    @GetMapping(value = "/myApplyList2")
    @PermissionData(pageComponent = "gudingzichan/GudingzichanMyApplyList2")
    public Result<?> queryYjTjList(Gudingzichan gudingzichan,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page = new Page<>(pageNo, pageSize);
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        if (gudingzichan.getPilbs()!=null||gudingzichan.getPilbs()!=""){
//            List<Gudingzichan>children=gudingzichanService.myApplyList2(user,gudingzichan);
//            gudingzichan.setChildren(children);
//        }
//        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page2 = new Page<>(pageNo, pageSize);
//
//        List<org.jeecg.modules.gudingzichan.entity.Gudingzichan> list = gudingzichanService.myApplyListTest( user, gudingzichan);
//        page2.setRecords(list);
//        if (page2.getTotal() > 0) {
//            page2.getRecords().forEach(record -> {
//                if (null != record.getEndTime()) {
//                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
//                } else {
//                    if (null != record.getAuditStatus()) {
//                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
//                    } else {
//                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
//                    }
//                }
//            });
//        }
//
//        page2.getRecords().stream().forEach(item -> {
//            // 前端显示完整层级的组织机构
//            String fullName = this.dig_parentId(item.getGuanlbm());
//            if(fullName.length() > 1)
//                fullName = fullName.substring(1);
//            item.setGuanlbm_fullName(fullName);
//
//            fullName = this.dig_parentId(item.getDeptId());
//            if(fullName.length() > 1)
//                fullName = fullName.substring(1);
//            item.setDeptId_fullName(fullName);
//        });

        return Result.ok(page);
    }

    /**
     * 添加
     *
     * @param gudingzichan
     * @return
     */
    @AutoLog(value = "gudingzichan-添加")
    @ApiOperation(value = "gudingzichan-添加", notes = "gudingzichan-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Gudingzichan gudingzichan) {
        Gudingzichan gudingzichan1=new  Gudingzichan();
        if (gudingzichan.getBianhao().equals((gudingzichan1.getBianhao()))){
            return Result.error("编号不得重复");
        }
        gudingzichan.setZichanStatus("1");
        String code = gudingzichan.getBianhao().substring(0, 11);
        int categoryCount = gudingzichanService.count(new LambdaQueryWrapper<Gudingzichan>().likeRight(Gudingzichan::getBianhao, code)) + 1;

        Integer shul = Integer.parseInt(gudingzichan.getShuliang());

        Gudingzichan gudingzichan2 = new Gudingzichan();
        for(int i = 0; i < shul; i++) {
            BeanUtils.copyProperties(gudingzichan, gudingzichan2);
            gudingzichan2.setJine(gudingzichan.getDanjia());
            gudingzichan2.setId(null);
            gudingzichan2.setShuliang("1");
            gudingzichan2.setBianhao(code + String.format("%06d", i + categoryCount));
            gudingzichan2.setDanjia(gudingzichan.getDanjia());
            if(gudingzichan.getUseStatus().trim().equals("在用"))
                gudingzichan2.setUseStatus("1");
            if(gudingzichan.getUseStatus().trim().equals("损毁待报废"))
                gudingzichan2.setUseStatus("2");
            if(gudingzichan.getUseStatus().trim().equals("闲置"))
                gudingzichan2.setUseStatus("3");
            if(gudingzichan.getUseStatus().trim().equals("出借"))
                gudingzichan2.setUseStatus("4");
            if(gudingzichan.getBmjb().trim().equals("校机关"))
                gudingzichan2.setBmjb("2375001");
            if(gudingzichan.getBmjb().trim().equals("院机关"))
                gudingzichan2.setBmjb("2395105");
            if(gudingzichan.getBmjb().trim().equals("直属中心"))
                gudingzichan2.setBmjb("2432501");
            if(gudingzichan.getBmjb().trim().equals("一部两系"))
                gudingzichan2.setBmjb("2797508");
            if(gudingzichan.getBmjb().trim().equals("教练勤务营"))
                gudingzichan2.setBmjb("2797508");
            if(gudingzichan.getBmjb().trim().equals("基层单位"))
                gudingzichan2.setBmjb("2797532");

            gudingzichanService.save(gudingzichan2);
            gudingzichan.setId(gudingzichan2.getId());
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            gudingzichanService.startFlow(gudingzichan2, loginUser);

        }
        return Result.ok(gudingzichan2);


    }

    /**
     * 添加
     *
     * @param gudingzichan
     * @return
     */
    @AutoLog(value = "gudingzichan-报销添加")
    @ApiOperation(value = "gudingzichan-报销添加", notes = "gudingzichan-报销添加")
    @PostMapping(value = "/BaoXiaoAdd")
    public Result<?> BaoXiaoAdd(@RequestBody Gudingzichan gudingzichan) {
        Gudingzichan gudingzichan1=new  Gudingzichan();
        if (gudingzichan.getBianhao().equals((gudingzichan1.getBianhao()))){
            return Result.error("编号不得重复");
        }
        gudingzichan.setZichanStatus("1");
        String code = gudingzichan.getBianhao().substring(0, 11);
        int categoryCount = gudingzichanService.count(new LambdaQueryWrapper<Gudingzichan>().likeRight(Gudingzichan::getBianhao, code)) + 1;

        Integer shul = Integer.parseInt(gudingzichan.getShuliang());

        Gudingzichan gudingzichan2 = new Gudingzichan();
        for(int i = 0; i < shul; i++) {
            BeanUtils.copyProperties(gudingzichan, gudingzichan2);
            gudingzichan2.setJine(gudingzichan.getDanjia());
            gudingzichan2.setId(null);
            gudingzichan2.setShuliang("1");
            gudingzichan2.setBianhao(code + String.format("%06d", i + categoryCount));
            gudingzichan2.setDanjia(gudingzichan.getDanjia());
            if(gudingzichan.getUseStatus().trim().equals("在用"))
                gudingzichan2.setUseStatus("1");
            if(gudingzichan.getUseStatus().trim().equals("损毁待报废"))
                gudingzichan2.setUseStatus("2");
            if(gudingzichan.getUseStatus().trim().equals("闲置"))
                gudingzichan2.setUseStatus("3");
            if(gudingzichan.getUseStatus().trim().equals("出借"))
                gudingzichan2.setUseStatus("4");

            gudingzichanService.save(gudingzichan2);
            gudingzichan.setId(gudingzichan2.getId());

        }
        return Result.ok(gudingzichan2);


    }

    /**
     * 编辑
     *
     * @param gudingzichan
     * @return
     */
    @AutoLog(value = "gudingzichan-编辑")
    @ApiOperation(value = "gudingzichan-编辑", notes = "gudingzichan-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Gudingzichan gudingzichan) {
        Gudingzichan gudingzichan1=new  Gudingzichan();
        if (gudingzichan.getBianhao().equals((gudingzichan1.getBianhao()))){
            return Result.error("编号不得重复");
        }
        gudingzichanService.updateById(gudingzichan);
        return Result.ok("编辑成功!");

    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "gudingzichan-通过id删除")
    @ApiOperation(value = "gudingzichan-通过id删除", notes = "gudingzichan-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        gudingzichanService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "gudingzichan-批量删除")
    @ApiOperation(value = "gudingzichan-批量删除", notes = "gudingzichan-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.gudingzichanService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "gudingzichan-通过id查询")
    @ApiOperation(value = "gudingzichan-通过id查询", notes = "gudingzichan-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Gudingzichan gudingzichan = gudingzichanService.getById(id);
        if (gudingzichan == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(gudingzichan);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param gudingzichan
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Gudingzichan gudingzichan, String type) {
//        HqGudzcDaorsjdygx hqGudzcDaorsjdygx=catchSysOrgCode(gudingzichan.getDeptId());
//        gudingzichan.setDeptId(hqGudzcDaorsjdygx.getSantyzzjgmc());
        return super.exportXls(request, gudingzichan, Gudingzichan.class, "gudingzichan");
    }

    @Autowired
    private IHqGudzcDaorsjdygxService hqGudzcDaorsjdygxService;

    // 参数导入文件中的部门名称,返回对应关系
    HqGudzcDaorsjdygx matchSysOrgCode(String daorbmmc) {
        HqGudzcDaorsjdygx hqGudzcDaorsjdygx = hqGudzcDaorsjdygxService.getOne(new LambdaQueryWrapper<HqGudzcDaorsjdygx>().eq(HqGudzcDaorsjdygx::getSantyzzjgbm, daorbmmc), false);
        if(hqGudzcDaorsjdygx != null)
            return hqGudzcDaorsjdygx;

        return null;
    }
//    //参数导出文件中的部门id，返回对应关系
//    HqGudzcDaorsjdygx catchSysOrgCode(String daocbmId){
//        HqGudzcDaorsjdygx hqGudzcDaorsjdygx=hqGudzcDaorsjdygxService.getOne(new LambdaQueryWrapper<HqGudzcDaorsjdygx>().eq(HqGudzcDaorsjdygx::getId,daocbmId));
//        if(hqGudzcDaorsjdygx != null)
//            return hqGudzcDaorsjdygx;
//
//        return null;
//    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Gudingzichan> list = ExcelImportUtil.importExcel(file.getInputStream(), Gudingzichan.class, params);

                int idx = 0;
                for (Gudingzichan element: list
                        ) {
                    idx++;
                    Gudingzichan gudingzichan = gudingzichanService.getOne(new LambdaQueryWrapper<Gudingzichan>().
                            eq(Gudingzichan::getBianhao, element.getBianhao()), false);
                    // 重复记录
                    if(gudingzichan != null) {
                        log.info("记录重复：" + element.getBianhao());
                        continue;
                    }

                    if(element.getUseStatus().trim().equals("在用"))
                        element.setUseStatus("1");
                    if(element.getUseStatus().trim().equals("损毁待报废"))
                        element.setUseStatus("2");
                    if(element.getUseStatus().trim().equals("闲置"))
                        element.setUseStatus("3");
                    if(element.getUseStatus().trim().equals("出借"))
                        element.setUseStatus("4");


                    // 类别
                    if(element.getCategoryId() != null) {
                        SysCategory sysCategory = sysCategoryService.getOne(new LambdaQueryWrapper<SysCategory>().eq(SysCategory::getCustomCode, element.getCategoryId().trim()), false);
                        if (sysCategory != null) {
                            element.setCategoryId(sysCategory.getId());
                        } else
                            element.setCategoryId(element.getCategoryId().trim());
                    }

                    // 原主管单位
                    if(element.getDeptId() != null) {
                        element.setYuanbgdw(element.getDeptId().trim());
                    }

                    // 原保管人
                    if(element.getBaoguanren() != null)
                        element.setYuanbgr(element.getBaoguanren().trim());
                        element.setBaoguanren(element.getBaoguanren().trim());

                    // 原资产名称
                    if(element.getZichanmingcheng() != null) {
                        //element.setYuanzcmc(element.getZichanmingcheng().trim());
                        element.setZichanmingcheng(element.getZichanmingcheng().trim());
                    }

                    // 原规格型号
                    if(element.getXinghao() != null) {
                        //element.setYuanggxh(element.getXinghao().trim());
                        element.setXinghao(element.getXinghao().trim());
                    }

                    String daorbmmc = "";
                    if(element.getGuanlbm() != null)
                        daorbmmc = element.getGuanlbm().trim();

                    // 使用部门名称匹配组织机构代码
                    HqGudzcDaorsjdygx hqGudzcDaorsjdygx = matchSysOrgCode(daorbmmc);
                    if(hqGudzcDaorsjdygx != null) {
                        // 使用部门
                        SysDepart sysDepart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode2, hqGudzcDaorsjdygx.getSantyzzjgbm()), false);
                        if(sysDepart != null) {
                            // 使用部门
                            element.setDeptId(sysDepart.getId());
                            // 管理部门
                            element.setGuanlbm(sysDepart.getId());

                            element.setSysOrgCode(sysDepart.getOrgCode());
                        } else
                            element.setDeptId(null);

                         //保管人
//                    if(element.getBaoguanren() != null) {
//                        element.setBaoguanren(element.getBaoguanren());
//                    }
                } else {
                    log.error("部门名称未匹配到三统一组织机构代码, {}", daorbmmc);
//                    element.setBaoguanren(null);
                }

//
//                    // 财务部门
//                    sysDepart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getDepartName, element.getCaiwbm().trim()), false);
//                    if(sysDepart != null) {
//                        element.setCaiwbm(sysDepart.getId());
//                    } else
//                        element.setCaiwbm(null);

                    // 获取方式
                    if(element.getYuanyin().trim().equals("自购或自建"))
                        element.setYuanyin("2");
                    if(element.getYuanyin().trim().equals("调剂"))
                        element.setYuanyin("3");
                    if(element.getYuanyin().trim().equals("捐赠"))
                        element.setYuanyin("4");
                    //使用状态
                    element.setZichanStatus("5");
                    log.info("保存结果: {}, {}", idx, gudingzichanService.save(element));
                }

                //update-begin-author:taoyan date:20190528 for:批量插入数据
//                long start = System.currentTimeMillis();
//                gudingzichanService.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据

                return Result.ok("文件导入成功！数据行数：" + list.size());

            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());

            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return Result.error("文件导入失败！");
    }


    @AutoLog(value = "我的申请-分页列表查询")
    @ApiOperation(value = "我的申请-分页列表查询", notes = "我的申请-分页列表查询")
    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {

        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> iPage = gudingzichanService.myApplyList(page, user, gudingzichan);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }

        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getGuanlbm());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setGuanlbm_fullName(fullName);

            fullName = this.dig_parentId(item.getDeptId());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setDeptId_fullName(fullName);

            List<org.jeecg.modules.gudingzichan.entity.Gudingzichan> list = gudingzichanService.list(new QueryWrapper<Gudingzichan>().eq("pilbs",item.getPilbs()));
//            IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> list = gudingzichanService.myApplyList(page,user,gudingzichan);
            List<org.jeecg.modules.gudingzichan.entity.GudingzichanChild> listChild =new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                GudingzichanChild child=new GudingzichanChild();
                BeanUtils.copyProperties(list.get(i), child);
                if (null != child.getEndTime()) {
                    child.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != child.getAuditStatus()) {
                        child.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        child.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
                String childfullName = this.dig_parentId(child.getGuanlbm());
                if(childfullName.length() > 1)
                    childfullName = childfullName.substring(1);
                child.setGuanlbm_fullName(childfullName);
                childfullName = this.dig_parentId(child.getDeptId());
                if(childfullName.length() > 1)
                    childfullName = childfullName.substring(1);
                child.setDeptId_fullName(childfullName);
                listChild.add(child);

            }

                    item.setChildren(listChild);


        });

        return Result.ok(iPage);
    }

    @AutoLog(value = "我的待办-分页列表查询")
    @ApiOperation(value = "我的待办-分页列表查询", notes = "我的待办-分页列表查询")
    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> iPage = gudingzichanService.myTodoTasks(page, user, gudingzichan);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }

        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getGuanlbm());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setGuanlbm_fullName(fullName);

            fullName = this.dig_parentId(item.getDeptId());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setDeptId_fullName(fullName);
        });

        return Result.ok(iPage);
    }

    /**
     * 分页列表查询
     *
     * @param gudingzichan
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "mytodolist2-分页列表查询")
    @ApiOperation(value = "gudingzichan-分页列表查询", notes = "mytodolist2-分页列表查询")
    @GetMapping(value = "/mytodolist2")
    @PermissionData(pageComponent = "gudingzichan/GudingzichanMytodolist2")
    public Result<?> mytodolist2(Gudingzichan gudingzichan,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> iPage = gudingzichanService.myTodoTasks2(page, user, gudingzichan);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }

        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getGuanlbm());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setGuanlbm_fullName(fullName);

            fullName = this.dig_parentId(item.getDeptId());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setDeptId_fullName(fullName);
        });

        return Result.ok(iPage);
    }

    @AutoLog(value = "我的已办-分页列表查询")
    @ApiOperation(value = "我的已办-分页列表查询", notes = "我的已办-分页列表查询")
    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> iPage = gudingzichanService.myDoneTasks(page, user, gudingzichan);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }
        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getGuanlbm());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setGuanlbm_fullName(fullName);

            fullName = this.dig_parentId(item.getDeptId());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setDeptId_fullName(fullName);
        });

        return Result.ok(page);
    }

    @AutoLog(value = "我的已办2-分页列表查询")
    @ApiOperation(value = "我的已办2-分页列表查询", notes = "我的已办2-分页列表查询")
    @GetMapping(value = "/mydonelist2")
    public Result<?> myDoneList2(org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> iPage = gudingzichanService.myDoneTasks2(page, user, gudingzichan);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }
        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getGuanlbm());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setGuanlbm_fullName(fullName);

            fullName = this.dig_parentId(item.getDeptId());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setDeptId_fullName(fullName);
        });

        return Result.ok(page);
    }

    @AutoLog(value = "任务审批")
    @ApiOperation(value = "任务审批", notes = "任务审批")
    @PostMapping(value = "/completetask")
    public Result<?> completeTask(@RequestBody Gudingzichan gudingzichan) {
        gudingzichanService.updateById(gudingzichan);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        gudingzichanService.complateTask(loginUser, gudingzichan.getTaskId(), gudingzichan.getProcessInstanceId(),
                Integer.parseInt(gudingzichan.getAuditStatus()), gudingzichan.getAuditMemo(),
                gudingzichan.getAuditUser(), Float.parseFloat(gudingzichan.getJine()),gudingzichan.getSqlx());

        return Result.ok("操作成功");
    }


    @PostMapping("/handleStatus")
    public Result<?> handleStatus(@RequestBody Gudingzichan gudingzichan) {
        gudingzichanService.handleStatus(gudingzichan);
        return Result.ok("添加成功！");
    }

    @PostMapping("/startTjYjStatus")
    public Result<?> startTjYjFlow(@RequestBody Gudingzichan gudingzichan) {
        gudingzichanService.handleTjYjStatus(gudingzichan);
        return Result.ok("添加成功！");
    }

    @GetMapping("/weizhiData")
    public Result<?> weizhiData() {
        List<DictModel> yqDictList = this.sysDictService.queryDictItemsByCode("ying_qu");
        Map tmpMap = new HashMap();
        Map tmp2Map = new HashMap();
        List<Map> weizhiData = new ArrayList<>();
        if (!CollectionUtils.isEmpty(yqDictList)) {
            yqDictList.forEach(dict -> {
                Map map = new HashMap();
                map.put("value", dict.getValue());
                map.put("label", dict.getText());
                tmpMap.put(dict.getValue(), map);
                weizhiData.add(map);
            });
        }
        List<HqLouy> lyList = this.hqLouyService.list();
        if (!CollectionUtils.isEmpty(lyList)) {
            Map<String, List<HqLouy>> groupMap = lyList.stream().collect(Collectors.groupingBy(HqLouy::getYingqId));
            groupMap.forEach((key, val) -> {
                Map tm = (Map) tmpMap.get(key);
                if (null != tm) {
                    tm.put("children", val.stream().map(hqLouy -> {
                        Map lyMap = new HashMap();
                        lyMap.put("value", hqLouy.getId());
                        lyMap.put("label", hqLouy.getName());
                        tmp2Map.put(hqLouy.getId(), lyMap);
                        return lyMap;
                    }).collect(Collectors.toList()));
                }
            });
        }

        List<HqYfFangj> fjList = this.hqYfFangjService.list();

        if (!CollectionUtils.isEmpty(fjList)) {
            Map<String,List<Map>> loucengMap = new HashMap<>();
            Map<String, List<Map>> groupMap = fjList.stream().collect(Collectors.groupingBy(HqYfFangj::getLouyId, Collectors.mapping(fangj -> {
                List<Map> list = loucengMap.get(fangj.getFloor());
                if(CollectionUtils.isEmpty(list)){
                   list = new ArrayList<Map>();
                }
                list.add(new HashMap(){{
                    put("value", fangj.getId());
                    put("label", fangj.getFloor() + "-" + fangj.getRoomnu());
                }});
                Map lcMap = new HashMap();
                lcMap.put("value",fangj.getFloor());
                lcMap.put("label",fangj.getFloor());
                lcMap.put("children",list);
                return lcMap;
            }, Collectors.toList())));
            groupMap.forEach((key, val) -> {
                Map tm = (Map) tmp2Map.get(key);
                if (null != tm) {
                    tm.put("children", val);
                }
            });
        }

        return Result.ok(weizhiData);
    }
//    @AutoLog(value = "gudingzichan-分页列表条件查询")
//    @ApiOperation(value = "gudingzichan-分页列表条件查询", notes = "gudingzichan-分页列表条件查询")
//    @GetMapping(value = "/queryByConditions")
//    public Result<?> queryByConditions(Gudingzichan gudingzichan,
//                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
//                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
//                                   HttpServletRequest req) {
//
//        Page<Gudingzichan> page = new Page<>(pageNo, pageSize);
//        QueryWrapper<Gudingzichan> queryWrapper = QueryGenerator.initQueryWrapper(gudingzichan, req.getParameterMap());
//        if(gudingzichan.getWeizhisgtx() != null && gudingzichan.getWeizhisgtx().trim() != "")
//            queryWrapper.like("weizhisgtx", gudingzichan.getWeizhisgtx());
//        QueryWrapper<Gudingzichan> wrapper=queryWrapper.orderByAsc("bianhao");
//        IPage<Gudingzichan> pageList=gudingzichanService.page(page,wrapper);
//
//        pageList.getRecords().stream().forEach(item -> {
//            // 前端显示完整层级的组织机构
//            String fullName = this.dig_parentId(item.getGuanlbm());
//            if(fullName.length() > 1)
//                fullName = fullName.substring(1);
//            item.setGuanlbm_fullName(fullName);
//
//            fullName = this.dig_parentId(item.getDeptId());
//            if(fullName.length() > 1)
//                fullName = fullName.substring(1);
//            item.setDeptId_fullName(fullName);
//        });
//
//        return Result.ok(pageList);
//    }
}
